package soulkun.library.utils.screen

import soulkun.library.LibraryInit
import kotlin.math.max

object DensityUtils {

    fun dp2px(dp: Float): Int {
        val density: Float = LibraryInit.context.resources.displayMetrics.density
        val px = (dp * density + 0.5f).toInt()
        return max(px, 1)
    }

    fun dp2pxF(dp: Float): Float {
        val density: Float = LibraryInit.context.resources.displayMetrics.density
        return dp * density
    }

    fun px2dp(px: Float): Int {
        val density: Float = LibraryInit.context.resources.displayMetrics.density
        val dp = (px / density + 0.5f).toInt()
        return max(dp, 1)
    }

    fun px2dpF(px: Float): Float {
        val density: Float = LibraryInit.context.resources.displayMetrics.density
        return px / density
    }

    fun sp2px(sp: Float): Int {
        val density: Float = LibraryInit.context.resources.displayMetrics.scaledDensity
        val px = (sp * density + 0.5f).toInt()
        return max(px, 1)
    }

    fun sp2pxF(sp: Float): Float {
        val density: Float = LibraryInit.context.resources.displayMetrics.scaledDensity
        return sp * density
    }

    fun px2sp(px: Float): Int {
        val density: Float = LibraryInit.context.resources.displayMetrics.scaledDensity
        val sp = (px / density + 0.5f).toInt()
        return Math.max(sp, 1)
    }

    fun px2spF(px: Float): Float {
        val density: Float = LibraryInit.context.resources.displayMetrics.scaledDensity
        return px / density
    }

    fun bytes2HexString(bytes: ByteArray): String? {
        val builder = StringBuilder()
        for (b in bytes) {
            val s = Integer.toHexString(b.toInt() and 0xFF)
            if (s.length < 2) {
                builder.append("0")
            }
            builder.append(s)
        }
        return builder.toString()
    }

}